<template>
    <ContentFieldVue>
        <div class="row justify-content-md-center">  <!-- 全文检索ctrl + f -->
            <div class="col-3">
                <form @submit.prevent="register"> <!-- 将提交和注册绑定 -->
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input v-model="password" type="password" class="form-control" id="password" placeholder="请输入密码">
                    </div>
                    <div class="mb-3">
                        <label for="confirmedPassword" class="form-label">确认密码</label>
                        <input v-model="confirmedPassword" type="password" class="form-control" id="confirmedPassword" placeholder="请再次输入密码">
                    </div>
                    <div class="error-message">{{ error_message }}</div>
                    <button type="submit" class="btn btn-primary">提交</button>
                </form>
            </div>
        </div>
    </ContentFieldVue>
</template>

<script> //{}是没有export default才要加
import ContentFieldVue from "@/components/ContentField.vue";
import { ref } from "vue";
import router from "@/router";
import $ from 'jquery';

export default {
    components: {
        ContentFieldVue
    },
    setup() {
        let username = ref('');
        let password = ref('');
        let confirmedPassword = ref('');
        let error_message = ref('');

        const register = () => {
            $.ajax({  // 不放进user.js因为不会修改user中的state值
                url: "https://app7167.acapp.acwing.com.cn/api/user/account/register/",
                type: "post", //获取修改数据用post， 只是获取数据用get
                data: {
                    username: username.value,
                    password: password.value,
                    confirmedPassword: confirmedPassword.value,
                },
                success(resp) {
                    if (resp.error_message === "success") {
                        router.push({name: "user_account_login"});
                    } else {
                        error_message.value = resp.error_message;
                    }
                },
            });
        }

        return {
            username,
            password,
            confirmedPassword,
            error_message,
            register,
        }
    }
}
</script>

<style scoped>
button {
    width: 100%;
}

div.error-message {
    color: red;
}
</style>